import React from 'react';
import { observer } from 'mobx-react';
import { Icon, Modal } from 'weaver-mobile';
import { ListPage } from 'weaver-mobile-page';
import {_, FieldUtil} from "../../../util/pcPublic";
import {getLabel, showFormAttach} from "../../../util/common";
import AddIcon from "./AddIcon";
import {toJS} from "mobx";

const alert = Modal.alert;

const ListPageNormal = ListPage.Normal;
const template = {
  default: [
    {
      key: 'col1',
      configs: [
        {
          key: 'col1_row1',
          configs: [
            { key: 'filename' },
          ],
        },
        {
          key: 'col1_row2',
          configs: [
            {
              key: 'username',
              style: { marginRight: '10px' },
            },
            {
              key: 'uploaddate',
            },
          ],
        },
      ],
    },
  ],
};

const list = new ListPage.Store();

@observer
export default class ReqWfFileUpload extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { fieldid, wfLayoutStore } = this.props;
    const { mainData } = wfLayoutStore;
    const fieldMark = `field${fieldid}`;
    let fieldObj = FieldUtil.getMainFieldObj(fieldMark, mainData);
    let specialobj  = fieldObj.specialobj ? toJS(fieldObj.specialobj) : {};
    const { filedatas = [] } = specialobj;
    filedatas.map(filedata => {
      filedata.id = filedata.fileid;
    })
    list.setState({ data: filedatas });
  }

  // 保存拖拽状态
  onSortEnd = (changeDatas) => {
    const { fieldid, wfLayoutStore } = this.props;
    const { mainData } = wfLayoutStore;
    const fieldMark = `field${fieldid}`;
    let fieldObj = FieldUtil.getMainFieldObj(fieldMark, mainData);
    const {specialobj = {}} = fieldObj;
    let nextfiledatas = [];
    let ids = [];
    changeDatas.map(changeData => {
      nextfiledatas.push(changeData);
      ids.push(changeData.fileid);
    });
    specialobj.filedatas = nextfiledatas;
    wfLayoutStore.changeSingleFieldValue(fieldMark, {value:ids.join(","), specialobj:specialobj});

    list.setState({ data: nextfiledatas });
  }

  onDel = () => {
    const { fieldid, wfLayoutStore } = this.props;
    if(list.selectedRowKeys.length > 0){
      alert('删除', '确认删除选中附件吗?', [
        { text: '取消', onPress: () => {} },
        { text: '确认', onPress: () => {
            const { mainData } = wfLayoutStore;
            const fieldMark = `field${fieldid}`;
            let fieldObj = FieldUtil.getMainFieldObj(fieldMark, mainData);
            //当前字段的只读、必填属性
            let viewAttr = FieldUtil.getFieldCurViewAttr(fieldMark, fieldObj);
            const {specialobj = {}} = fieldObj;
            let nextfiledatas = [];
            let ids = [];
            specialobj.filedatas && specialobj.filedatas.map(item => {
              if(list.selectedRowKeys.indexOf(item.fileid) == -1){
                nextfiledatas.push(item);
                ids.push(item.fileid);
              }
            });
            specialobj.filedatas = nextfiledatas;
            wfLayoutStore.changeSingleFieldValue(fieldMark, {value:ids.join(","), specialobj:specialobj});

            list.setState({ data: nextfiledatas });
          }
        }
      ])
    }
  }

  onView = (file) => {
    const { fieldid, wfLayoutStore } = this.props;
    const { fieldAttrMap } = wfLayoutStore;
    const fieldAttr = fieldAttrMap.get(fieldid);
    const { detailtype } = fieldAttr;
    showFormAttach(file, {}, "/req", detailtype);
  }

  onDownload = (file) => {
    window.WfForm.downLoadFile(file.imagefileid, "/req");
  }

  render() {
    return (<div className="wf-req-filelist" >
      <div className="wf-req-filelist-content">
        {this.getListHead()}
        <ListPageNormal
          withSwipeAction={true}
          swipeActionProps={{
            right: [{
              text: '下载',
              style: { color: '#fff', width: '45px' },
              onPress: this.onDownload,
            }],
          }}
          showCheck
          multipleCheck
          sortable
          onSortEnd={this.onSortEnd}
          onRowClick={this.onView}
          template={template}
          store={list}
        />
      </div>
    </div>
    );
  }

  getListHead = () => {
    const { fieldid, wfLayoutStore, wfGlobalStore } = this.props;
    const { mainData, fieldAttrMap } = wfLayoutStore;
    const fieldMark = `field${fieldid}`;
    let fieldObj = FieldUtil.getMainFieldObj(fieldMark, mainData);
    //计算字段类型(支持动态切换字段类型)
    const fieldAttr = fieldAttrMap.get(fieldid);
    //字段值,特殊字符转换
    const { fileattr } = fieldAttr;
    //当前字段的只读、必填属性
    let viewAttr = FieldUtil.getFieldCurViewAttr(fieldMark, fieldObj);
    //计算附件上传目录
    let { catelogType,docCategory }  = fileattr;
    let title = [];
    let selectedCatalog = {};
    if(catelogType === 0){
      if(_.trim(docCategory).length == 0){
        title = <span style={{ marginRight: "5px", color: "red" }}>{getLabel(83157,"附件上传目录未设置!")}</span>;
      }
    }else{
      selectedCatalog = this.getFileSelectedCatalog();
      if(_.isEmpty(selectedCatalog)){
        title = <span style={{ marginRight: "5px", color: "red" }}>{getLabel(83157,"附件上传目录未设置!")}</span>;
      }else{
        if(selectedCatalog.errorMsg){
          title = <span style={{ marginRight: "5px", color: "red" }}>{selectedCatalog.errorMsg}</span>;
        }
      }
    }

    if(viewAttr == 3 && list.data.length == 0 && title.length == 0){
      title = <span style={{ marginRight: "5px", color: "red" }}>（必填）</span>;
    }
    let showAdd = true;
    let showDelete = true;
    if(viewAttr == 1){
      showAdd = false;
      showDelete = false;
    }
    const selectedRowNum = list.selectedRowKeys.length;

    return (
        <div style={{height:'28px', lineHeight:'28px', width:"100%", margin:"10px 0px" }}>
          {title}
          {showDelete && <div
            style={{ width: '28px', height: '28px', float: 'right', marginRight: "5px" }}>
            <Icon type="minus" size="xs" color="white" onClick={this.onDel}
             style={{background: selectedRowNum == 0 ? '#d8d8d8':'#55b1f9', width: '18px', height: '18px', padding: '5px'}} /></div>}
          {showAdd && <div
            style={{ width: '28px', height: '28px', float: 'right', marginRight: "5px" }}>
            <AddIcon fieldid={fieldid} wfLayoutStore={wfLayoutStore} wfGlobalStore={wfGlobalStore} listStore={list}
           /></div>}
        </div>
    );
  }

  //获取附件字段对应的选择框目录信息
  getFileSelectedCatalog = () => {
    const { fieldid, wfLayoutStore } = this.props;
    const { fieldAttrMap } = wfLayoutStore;
    const fieldAttr = fieldAttrMap.get(fieldid);
    const { fileattr } = fieldAttr || {};
    const selectedFieldid = fileattr.selectedCateLog;
    if(fileattr.catelogType !== 1 || !selectedFieldid || !fieldAttrMap.has(selectedFieldid))      //附件字段非选择框控制目录
      return {};

    const selectedFieldValue = FieldUtil.getRelateFieldValue(selectedFieldid, '');
    const selectedFieldAttr = fieldAttrMap.get(selectedFieldid);
    const { fieldlabel,selectattr } = selectedFieldAttr;

    let selectedCatalog = {};
    if(selectedFieldid !== "" && selectedFieldValue !== ""){
      selectattr && selectattr.selectitemlist.map(v =>{
        if(v && v.selectvalue.toString() === selectedFieldValue.toString())
          selectedCatalog = {docCategory:v.docCategory, maxUploadSize:v.maxUploadSize||5};
      });
    }else{
      selectedCatalog.errorMsg = getLabel(125389,'请先选择"') +fieldlabel+'"';
    }
    return selectedCatalog;
  }

}
